import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
import useUserStore from '@/store/modules/user';
import Cookies from 'js-cookie';
import { localStorage } from '@/utils/storage';
import { signatureGenerate } from '@/utils/signatureUtil';
import cache from '@/plugins/cache';
const post = function (url, params) {
  const query = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 300000,
    data: params,
    headers: {
      'Content-Type': 'application/json',
      'request-ajax': true,
      token: Cookies.get(import.meta.env.VITE_APP_TOKEN_KEY)
    }
  };
  return request(false, query);
};

const postSync = async function (url: any, params: any) {
  const query: any = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 300000,
    data: params,
    headers: {
      'Content-Type': 'application/json',
      'request-ajax': true,
      token: Cookies.get(import.meta.env.VITE_APP_TOKEN_KEY)
    }
  };
  const queryParam = { ...query };
  const { signature, timestamp } = signatureGenerate(query);
  // 分别将签名、密钥、时间戳 至请求头
  if (signature) queryParam.headers['signature'] = signature;
  if (timestamp) queryParam.headers['timestamp'] = timestamp;
  const res = await axios.request(queryParam).catch(e => {
    ElMessage({
      message: e.message,
      type: 'error'
    });
    return Promise.reject(e.message);
  });
  return res.data;
};

// const postWithLoadTip = function (url, params) {
//   const query = {
//     url: url,
//     method: 'post',
//     withCredentials: true,
//     timeout: 30000,
//     data: params,
//     headers: {
//       'Content-Type': 'application/json',
//       'request-ajax': true,
//       token: Cookies.get(import.meta.env.VITE_APP_TOKEN_KEY)
//     }
//   };
//   return request(true, query);
// };
const postWithLoadTip = function (
  url: any,
  params: any,
  method = 'post',
  headers: object = {}
) {
  const query = {
    url: url,
    method: method,
    withCredentials: true,
    timeout: 300000,
    data: params,
    headers: {
      ...headers,
      'Content-Type': 'application/json',
      'request-ajax': true,
      token: Cookies.get(import.meta.env.VITE_APP_TOKEN_KEY)
    }
  };
  return request(true, query);
};
const postWithTimeOut = function (url, params) {
  const query = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 3000000,
    data: params,
    headers: {
      'Content-Type': 'application/json',
      'request-ajax': true,
      token: Cookies.get(import.meta.env.VITE_APP_TOKEN_KEY)
    }
  };
  return request(true, query);
};

const postWithOutLoadTip = function (url, params) {
  const query = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 300000,
    data: params,
    headers: {
      'Content-Type': 'application/json',
      'request-ajax': true,
      token: Cookies.get(import.meta.env.VITE_APP_TOKEN_KEY)
    }
  };
  return request(false, query);
};

const get = function (url, params) {
  const query = {
    url: url,
    method: 'get',
    withCredentials: true,
    timeout: 300000,
    params: params,
    headers: {
      'request-ajax': true,
      token: Cookies.get(import.meta.env.VITE_APP_TOKEN_KEY)
    }
  };
  return request(false, query);
};

const form = function (url, params) {
  const query = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 300000,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data',
      'request-ajax': true,
      token: Cookies.get(import.meta.env.VITE_APP_TOKEN_KEY)
    }
  };
  return request(false, query);
};

const request = function (loading, query) {
  //防止重复请求
  const requestObj = {
    url: query.url,
    data:
      typeof query.data === 'object' ? JSON.stringify(query.data) : query.data,
    time: new Date().getTime()
  };
  const sessionObj = cache.session.getJSON('sessionObj');
  if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
    cache.session.setJSON('sessionObj', requestObj);
  } else {
    const s_url = sessionObj.url; // 请求地址
    const s_data = sessionObj.data; // 请求数据
    const s_time = sessionObj.time; // 请求时间
    const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
    if (
      s_data === requestObj.data &&
      requestObj.time - s_time < interval &&
      s_url === requestObj.url
    ) {
      const message = '数据正在处理，请勿重复提交';
      // console.warn(`[${s_url}]: ` + message);
      return Promise.resolve({
        message: message
      });
    } else {
      cache.session.setJSON('sessionObj', requestObj);
    }
  }
  //防止重复请求
  let loadingShow: any = {};
  if (loading) {
    loadingShow = ElLoading.service({
      lock: false,
      background: 'rgba(0, 0, 0, 0.5)'
    });
  }
  const queryParam = { ...query };
  const { signature, timestamp } = signatureGenerate(query);
  // 分别将签名、密钥、时间戳 至请求头
  if (signature) queryParam.headers['signature'] = signature;
  if (timestamp) queryParam.headers['timestamp'] = timestamp;
  return axios
    .request(queryParam)
    .then(res => {
      if (res.data.code === 400 || res.data.code === 401) {
        useUserStore().removeLoginCookies();
        localStorage.clear();
        window.location.href = '/';
      } else if (res.data.code === 500) {
        return Promise.reject(res.data);
      } else if (res.data.code === 501) {
        return Promise.reject(res.data);
      } else if (res.data.code === 502) {
        useUserStore().removeLoginCookies();
        localStorage.clear();
        window.location.href = '/';
        return Promise.reject(null);
      } else {
        return Promise.resolve(res.data);
      }
    })
    .catch(e => {
      if (e !== null) {
        ElMessage({
          message: e.message,
          type: 'error'
        });
        return Promise.reject(e.message);
      } else {
        return Promise.reject(null);
      }
    })
    .finally(() => {
      if (loading) {
        loadingShow.close();
      }
    });
};

export {
  post,
  postWithLoadTip,
  postWithOutLoadTip,
  postWithTimeOut,
  postSync,
  get,
  form
};
